package logicGame.States;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Random;
import logicGame.*;

public class Auction extends StateAdapter implements Serializable {

    ArrayList<Player> bet, winner;

    public Auction(Game g) {
        super(g);
        bet = new ArrayList();
        winner = new ArrayList();
    }

    @Override
    public State bet(int coins, Player p) {
        if (bet.size() < getGame().getnPlayers()) {
            bet.add(p);
            p.setCoinsBet(coins);
            if (bet.size() < getGame().getnPlayers()) {
                getGame().nextPlayer();
            }
        }
        if (bet.size() == getGame().getnPlayers()) {
            championship();
            return new BuyCard(getGame());
        }
        return this;
    }

    private void championship() {
        winner.add(bet.get(0));
        for (int i = 0; i < bet.size(); i++) {
            if (bet.get(i).getCoinsBet() > winner.get(0).getCoinsBet()) {
                winner.removeAll(winner);
                winner.add(bet.get(i));
            } else if (bet.get(i).getCoinsBet() == winner.get(0).getCoinsBet()) {
                winner.add(bet.get(i));
            }
        }
        if (winner.size() == 1) {
            winner.get(0).setCoin(-winner.get(0).getCoinsBet());
            getGame().setActivePlayer(winner.get(0));
        } else {
            Random randomGenerator = new Random();
            int rand = randomGenerator.nextInt(winner.size());
            winner.get(rand).setCoin(-winner.get(rand).getCoinsBet());
            getGame().setActivePlayer(winner.get(rand));
        }

    }
}
